<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('encryptkey()'))
{
	function encryptkey()
	{
		$CI =& get_instance();
		return $CI->config->item('encryption_key');
	}
}

if ( ! function_exists('admin_login()'))
{
	function admin_login()
	{
		$CI =& get_instance();
		return $CI->session->userdata('admin_'.encryptkey());
	}
}

if ( ! function_exists('get_user()'))
{
	function get_user($a='')
	{
		$CI =& get_instance();
		$ses = array(
			'user_id'		=> $CI->session->userdata('user_id'),
			'name' 			=> $CI->session->userdata('name'),
			'tipe'			=> $CI->session->userdata('tipe'),
			'kantor'		=> get_kantor($CI->session->userdata('kantor'))
		);
		if(!$CI->session->userdata('admin_'.encryptkey()))
			return false;
			else{
				if($a == ''){
					return $ses;
				} else return $ses[$a];
			} 
	}
}

if ( ! function_exists('admin_login_cek()'))
{
	function admin_login_cek($uname='',$pwd='')
	{
		$CI =& get_instance();
		$ds = $CI->db->get_where('users', array('name' => $uname));
		if($ds->num_rows() == 1){
			$ds = $ds->result_array();
			$ds = $ds[0];
			if(md5($pwd) == $ds['password']){
				admin_sess_register($ds);
				return true;
			}else return false;
		}else return false;
	}
}

if ( ! function_exists('admin_sess_register()'))
{
	function admin_sess_register($data=array())
	{
		$CI =& get_instance();
		$CI->session->set_userdata(array('admin_'.encryptkey() => true));
		$CI->session->set_userdata($data);
	}
}

if ( ! function_exists('admin_logout()'))
{
	function admin_logout()
	{
		$CI =& get_instance();
		$CI->session->set_userdata(array('admin_'.encryptkey() => false));
		$CI->session->sess_destroy();
	}
}

function get_kantor($id){
	$d = array();
	if($id!=0){
		$CI =& get_instance();
		$kantor = $CI->db->get_where('mst_bp3tki',array('bp_id'=>$id))->row();
		$prov 	= $CI->db->group_by('prov_id')->get_where('v_bp3_kota',array('bp_id'=>$id));
		$kota	= $CI->db->get_where('v_bp3_kota',array('bp_id'=>$id));
		$kk = $provk = array();
		foreach($kota->result() as $k){
			$kk[$k->prov_id][] = array($k->kk_id,$k->kk_nama);
		}
		foreach($prov->result() as $k){
			$provk[] = array(
				'prov_id'	=> $k->prov_id,
				'prov_nama'	=> $k->prov_nama,
				'kota'		=> $kk[$k->prov_id]
			);
		}
		$d = array(
			'kantor' 	=> array($kantor->bp_id,$kantor->bp_nama),
			'prov'		=> $provk
		);
	}
	return $d;
}